package com.blazhovsky.mk.androidlan;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import android.os.AsyncTask;

public class Server
{
	MainActivity context;
	MyAsyncTask serv;

	ServerSocket serverSocket = null;
	boolean server = true;

	public Server(MainActivity c)
	{
		this.context = c;
	}

	public void pocni()
	{
		serv = new MyAsyncTask();
		serv.execute();
	}

	class MyAsyncTask extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected void onPreExecute()
		{

			super.onPreExecute();
			try
			{
				serverSocket = new ServerSocket(8888);
				System.out.println("Listening :8888");
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		@Override
		protected Void doInBackground(Void... params)
		{
			System.out.println("Pocnuva serverot");
			while (server)
			{
				try
				{

					System.out.println("Cekame...");
					serverSocket.setSoTimeout(100000);
					System.out.println("server ip: " + serverSocket.getLocalSocketAddress());

					Socket socketZaPrimanje = serverSocket.accept();

					NitkaZaPrimanje n = new NitkaZaPrimanje(context, socketZaPrimanje);
					n.pocni();
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println("Zavrsi serverot");
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			if (serverSocket != null)
			{
				try
				{
					serverSocket.close();
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
